package com.livi.security.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.livi.security.mapper.sys.SysUserMapper;
import com.livi.security.model.commom.BaseResponse;
import com.livi.security.model.commom.ResultCode;
import com.livi.security.model.sys.SysUser;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @Description: 登录成功处理逻辑
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	@Autowired
	SysUserMapper sysUserMapper;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Authentication authentication) throws IOException, ServletException {
		// 更新用户表上次登录时间
		User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Integer userId = Integer.parseInt(userDetails.getUsername());
		SysUser sysUser = new SysUser();
		sysUser.setUserId(userId);
		sysUser.setLastLoginTime(new Date());
		sysUserMapper.updateByPrimaryKeySelective(sysUser);

		// 此处还可以进行一些处理，比如登录成功之后可能需要返回给前台当前用户有哪些菜单权限，
		// 进而前台动态的控制菜单的显示等，具体根据自己的业务需求进行扩展

		// 返回json数据
		String res = JSONObject.toJSONString(new BaseResponse<>(true, ResultCode.LOGIN_SUCCESS));// 200,认证成功
		httpServletResponse.setContentType("text/json;charset=utf-8");
		httpServletResponse.getWriter().write(res);
	}
}
